package edu.lingnan.store.filters;

import edu.lingnan.store.entity.User;
import edu.lingnan.store.service.UserService;
import edu.lingnan.store.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author duan
 * JWT登录授权过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenAuth}")
    private String tokenAuth;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("JwtAuthenticationTokenFilter->doFilterInternal");
        String url =  request.getRequestURI();
        //登录注册找回密码相关请求，获取商品列表请求放行
        if(url != null){
            if("/user/login".equals(url)
                    || "/user/register".equals(url)
                    || "/product/allProduct".equals(url)
                    || "/upload/sendCode".equals(url)
                    || "/user/resetPassword".equals(url)
                    || "/goodsType/parentList".equals(url)
            ){
                filterChain.doFilter(request,response);
                return;
            }
        }
        //OPTIONS请求放行
        if(request.getMethod().equals("OPTIONS")){
            filterChain.doFilter(request, response);
        }
        //header没带token的，直接放过，因为部分url匿名用户也可以访问
        //如果需要不支持匿名用户的请求没带token，这里放过也没问题，因为SecurityContext中没有认证信息，后面会被权限控制模块拦截
        //1.获取请求头中关于tokenAuth的内容
        String auth = request.getHeader(tokenAuth);
        //2.如果没有指定的请求头直接放行
        if (auth != null && auth.startsWith(tokenHead)) {
            //auth中的内容是由tokenHead和token拼接而成
            String token = auth.substring(tokenHead.length());
            //从token中获取用户名
            String username = jwtTokenUtil.getUserNameFromToken(token);
            log.info("正在验证用户username: {}", username);
            //用户名不为null，且没有登录过
            if (username != null) {
                User userDetails = userService.loadUserByLoginName(username);
                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    //验证成功，放行
                    filterChain.doFilter(request, response);
                }
            }
        }
    }
}